<template>
  <el-dialog 
    title="配置计算规则" 
    :visible.sync="dialogVisible"
    width="1000px"
    append-to-body
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <el-form :model="localRule" label-width="120px" class="calc-rule-form" ref="calcForm">
      <el-form-item label="依赖参数" prop="dependencies" required>
        <el-transfer
          v-model="localRule.dependencies"
          :data="dependencyOptions"
          :titles="['可选参数', '已选参数']"
          :props="{
            key: 'paramCode',
            label: 'displayLabel'
          }"
          filterable
          @change="handleDependenciesChange"
          style="width: 100%;"
        >
          <!-- 自定义左侧内容 -->
          <template #default="{ option }">
            <div class="param-item">
              <div class="param-main">
                <span class="param-name">{{ option.paramName }}</span>
                <span class="param-code">({{ option.paramCode }})</span>
              </div>
              <div class="param-meta">
                <el-tag size="mini" type="info">{{ option.groupPath }}</el-tag>
                <span class="param-unit" v-if="option.unit">{{ option.unit }}</span>
                <span v-if="option.isMultiMeasure" class="multi-measure-tag">
                  <el-tag size="mini" type="warning">多测次({{ option.multiMeasureCount }})</el-tag>
                </span>
              </div>
            </div>
          </template>
          
          <!-- 自定义右侧内容 -->
          <template #right-footer>
            <div class="selected-count">
              已选择 {{ localRule.dependencies.length }} 个参数
            </div>
          </template>
        </el-transfer>
        <div class="form-tips">提示：显示所有参数组中的基础参数，可跨组选择依赖参数</div>
      </el-form-item>

      <!-- 多测次参数访问提示 -->
      <el-form-item label="多测次参数访问" v-if="hasMultiMeasureParams">
        <div class="multi-measure-tips">
          <p><i class="el-icon-info"></i> 当前依赖的多测次参数访问格式：</p>
          <div 
            v-for="param in multiMeasureDeps" 
            :key="param.paramCode" 
            class="param-access-example"
          >
            <div class="param-info">
              <strong>{{ param.paramName }}</strong> 
              <span class="param-location">({{ param.groupPath }})</span>
            </div>
            <div class="access-format">
              访问格式：{{ param.paramCode }}[0].value ~ 
              {{ param.paramCode }}[{{ param.multiMeasureCount - 1 }}].value
            </div>
          </div>
          <div class="access-tips">
            <p><strong>使用示例：</strong></p>
            <p>• 计算3次测量的平均值：AVG({{ multiMeasureDeps[0]?.paramCode || 'param' }}[0].value, 
            {{ multiMeasureDeps[0]?.paramCode || 'param' }}[1].value, {{ multiMeasureDeps[0]?.paramCode || 'param' }}[2].value)</p>
            <p>• 取第一次测量值：{{ multiMeasureDeps[0]?.paramCode || 'param' }}[0].value</p>
            <p>• 计算最大值：MAX({{ multiMeasureDeps[0]?.paramCode || 'param' }}[0].value, 
            {{ multiMeasureDeps[0]?.paramCode || 'param' }}[1].value, {{ multiMeasureDeps[0]?.paramCode || 'param' }}[2].value)</p>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="计算表达式" prop="calculationExpr" required>
        <el-input
          v-model="localRule.calculationExpr"
          type="textarea"
          :rows="4"
          placeholder="请输入计算表达式，如：ROUND(yield_load * 1000 / (3.1416 * POW(nominal_diameter/2, 2)), 1)"
          class="calc-expr-input"
          resize="none"
          @input="handleExpressionInput"
        ></el-input>
        <div class="form-tips">
          <p><strong>支持语法：</strong></p>
          <div class="syntax-grid">
            <div class="syntax-category">
              <strong>运算符</strong>
              <div>+、-、*、/、()</div>
            </div>
            <div class="syntax-category">
              <strong>数学函数</strong>
              <div>ROUND(值,精度)</div>
              <div>SUM(参数1,...)</div>
              <div>AVG(参数1,...)</div>
              <div>MAX()、MIN()</div>
              <div>ABS()、SQRT()</div>
              <div>POW(底数,指数)</div>
            </div>
            <div class="syntax-category">
              <strong>参数访问</strong>
              <div>普通参数：param_code</div>
              <div>多测次：param_code[0].value</div>
            </div>
            <div class="syntax-category">
              <strong>安全函数</strong>
              <div>SAFE_DIV(被除数,除数)</div>
              <div>避免除零错误</div>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="表达式校验">
        <div class="validate-controls">
          <el-button 
            type="info" 
            size="mini"
            @click="handleValidate"
            :loading="validateLoading"
            icon="el-icon-check"
            :disabled="!localRule.calculationExpr.trim()"
          >
            校验表达式
          </el-button>
          <el-button 
            type="text" 
            size="mini"
            @click="insertExample"
            icon="el-icon-question"
          >
            插入示例
          </el-button>
        </div>
        <div v-if="validateResult" :class="['validate-result', validateSuccess ? 'success' : 'error']">
          <i :class="validateSuccess ? 'el-icon-success' : 'el-icon-error'"></i>
          {{ validateResult }}
        </div>
      </el-form-item>

      <!-- 依赖参数预览 -->
      <el-form-item label="依赖预览" v-if="localRule.dependencies.length > 0">
        <div class="dependencies-preview">
          <el-tag 
            v-for="depCode in localRule.dependencies" 
            :key="depCode"
            size="small"
            type="info"
            class="dependency-tag"
            closable
            @close="removeDependency(depCode)"
          >
            {{ getParamDisplayName(depCode) }}
          </el-tag>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSave"
        :disabled="!validateSuccess && localRule.calculationExpr.trim()"
        :loading="saving"
      >
        {{ validateSuccess ? '确定' : '强制保存' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from 'lodash';

export default {
  name: 'CalcRuleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rule: {
      type: Object,
      required: true,
      default: () => ({
        dependencies: [],
        calculationExpr: ''
      })
    },
    baseParams: {
      type: Array,
      default: () => []
    },
    hasMultiMeasureParams: {
      type: Boolean,
      default: false
    },
    multiMeasureDeps: {
      type: Array,
      default: () => []
    },
    validateLoading: {
      type: Boolean,
      default: false
    },
    validateResult: {
      type: String,
      default: ''
    },
    validateSuccess: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      localRule: this.getDefaultRule(),
      saving: false
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    },
    
    // 依赖参数选项
    dependencyOptions() {
      return this.baseParams.map(param => ({
        ...param,
        displayLabel: `${param.paramName} (${param.paramCode}) - ${param.groupPath}`
      }));
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.initLocalRule();
        }
      },
      immediate: true
    },
    rule: {
      handler() {
        if (this.visible) {
          this.initLocalRule();
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取默认规则
    getDefaultRule() {
      return {
        dependencies: [],
        calculationExpr: ''
      };
    },

    // 初始化本地规则
    initLocalRule() {
      this.localRule = cloneDeep(this.rule) || this.getDefaultRule();
    },

    // 获取参数显示名称
    getParamDisplayName(paramCode) {
      const param = this.baseParams.find(p => p.paramCode === paramCode);
      if (param) {
        let displayName = param.paramName;
        if (param.unit) {
          displayName += ` (${param.unit})`;
        }
        if (param.isMultiMeasure) {
          displayName += ` [${param.multiMeasureCount}次]`;
        }
        return displayName;
      }
      return paramCode;
    },

    // 处理依赖参数变更
    handleDependenciesChange() {
      // 发出依赖参数变更事件，传递当前依赖参数
      this.$emit('dependencies-change', cloneDeep(this.localRule.dependencies));
    },

    // 移除单个依赖参数
    removeDependency(depCode) {
      const index = this.localRule.dependencies.indexOf(depCode);
      if (index > -1) {
        this.localRule.dependencies.splice(index, 1);
        this.handleDependenciesChange();
      }
    },

    // 处理表达式输入
    handleExpressionInput() {
      // 实时校验可以在这里实现
    },

    // 处理表达式校验
    handleValidate() {
      // 发出校验事件，传递当前表达式
      this.$emit('validate', cloneDeep(this.localRule.calculationExpr));
    },

    // 插入示例表达式
    insertExample() {
      if (this.localRule.dependencies.length > 0) {
        const firstDep = this.localRule.dependencies[0];
        const param = this.baseParams.find(p => p.paramCode === firstDep);
        
        if (param) {
          if (param.isMultiMeasure && param.multiMeasureCount > 1) {
            // 多测次参数示例
            const indexes = Array.from({ length: Math.min(3, param.multiMeasureCount) }, (_, i) => i);
            const paramsList = indexes.map(i => `${param.paramCode}[${i}].value`).join(', ');
            this.localRule.calculationExpr = `ROUND(AVG(${paramsList}), 2)`;
          } else {
            // 普通参数示例
            this.localRule.calculationExpr = `ROUND(${param.paramCode} * 1.0, 2)`;
          }
        }
      } else {
        // 通用示例
        this.localRule.calculationExpr = 'ROUND(SUM(param1, param2) / COUNT(param1, param2), 2)';
      }
    },

    // 处理保存
    handleSave() {
      this.saving = true;
      
      // 发出保存事件，传递本地规则
      this.$emit('save', cloneDeep(this.localRule));
      
      // 延迟关闭对话框，确保父组件有足够时间处理
      setTimeout(() => {
        this.dialogVisible = false;
        this.saving = false;
      }, 100);
    },

    // 处理取消
    handleCancel() {
      this.dialogVisible = false;
    },

    // 处理对话框关闭
    handleClose() {
      // 重置本地规则
      this.localRule = this.getDefaultRule();
      // 重置表单验证
      if (this.$refs.calcForm) {
        this.$refs.calcForm.clearValidate();
      }
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style scoped>
.calc-rule-form {
  margin-top: 10px;
}

.calc-rule-form .el-form-item {
  margin-bottom: 20px;
}

.calc-expr-input {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}

.form-tips {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
  background: #f4f4f5;
  padding: 8px 12px;
  border-radius: 4px;
}

.form-tips p {
  margin: 4px 0;
}

/* 语法网格布局 */
.syntax-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 8px;
}

.syntax-category {
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.syntax-category strong {
  display: block;
  margin-bottom: 6px;
  color: #303133;
}

.syntax-category div {
  font-size: 11px;
  color: #606266;
  margin: 2px 0;
}

/* 参数项样式 */
.param-item {
  padding: 8px 0;
  width: 100%;
}

.param-main {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.param-name {
  font-weight: 500;
  color: #303133;
  margin-right: 8px;
}

.param-code {
  font-size: 12px;
  color: #909399;
}

.param-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.param-unit {
  font-size: 11px;
  color: #67c23a;
  background: #f0f9ff;
  padding: 1px 6px;
  border-radius: 3px;
}

.multi-measure-tag {
  margin-left: 4px;
}

/* 多测次提示样式 */
.multi-measure-tips {
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 12px;
  font-size: 12px;
}

.param-access-example {
  margin: 8px 0;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.param-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.param-location {
  font-size: 11px;
  color: #909399;
}

.access-format {
  font-family: 'Consolas', 'Monaco', monospace;
  color: #e6a23c;
}

.access-tips {
  margin-top: 8px;
  padding: 8px;
  background: #e6f7ff;
  border-radius: 3px;
  font-style: italic;
}

.access-tips p {
  margin: 4px 0;
  font-size: 11px;
}

/* 校验结果样式 */
.validate-controls {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
}

.validate-result {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
}

.validate-result.success {
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
}

.validate-result.error {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  color: #f56c6c;
}

.validate-result i {
  margin-right: 6px;
}

/* 依赖参数预览 */
.dependencies-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  min-height: 40px;
}

.dependency-tag {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selected-count {
  padding: 10px;
  text-align: center;
  color: #909399;
  font-size: 12px;
  border-top: 1px solid #ebeef5;
}

/* 传输组件样式调整 */
:deep(.el-transfer-panel) {
  width: 320px;
}

:deep(.el-transfer-panel__list) {
  height: 300px;
}

:deep(.el-transfer-panel__item) {
  display: flex!important;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  margin-bottom: 10px;
}
:deep(.el-transfer-panel__item.el-checkbox .el-checkbox__label) {
  line-height: 20px;
}


:deep(.el-transfer-panel__filter) {
  margin: 10px;
}

:deep(.el-transfer__buttons) {
  padding: 0 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .syntax-grid {
    grid-template-columns: 1fr;
  }
  
  :deep(.el-transfer-panel) {
    width: 280px;
  }
}
</style>